﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WyUnity.Utility.ExtentionMethods
{

	/// <summary>
	/// String extensions
	/// </summary>
	public static class StringExtensions
	{
		#region Functions

		#region FromBase64

		/// <summary>
		/// 将用Base64编码字符串还原
		/// <param name="input">输入字符串</param>
		/// <param name="encodingUsing">默认编码UTF-8</param>
		/// </summary>
		public static string FromBase64(this string input, Encoding encodingUsing = null)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			byte[] tempArray = Convert.FromBase64String(input);
			return encodingUsing.NullCheck(Encoding.UTF8).GetString(tempArray);
		}

		/// <summary>
		/// 从Base64字符串转化为字节数组
		/// </summary>
		public static byte[] FromBase64(this string input)
		{
			return string.IsNullOrEmpty(input) ? new byte[0] : Convert.FromBase64String(input);
		}

		#endregion

		#region Left

		/// <summary>
		/// 截取字符串左边的n个字符
		/// </summary>
		public static string Left(this string input, int length)
		{
			return string.IsNullOrEmpty(input) ? "" : input.Substring(0, input.Length > length ? length : input.Length);
		}

		#endregion

		#region Right

		/// <summary>
		/// 截取字符串右边的n个字符
		/// </summary>
		public static string Right(this string input, int length)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			length = input.Length > length ? length : input.Length;
			return input.Substring(input.Length - length, length);
		}

		#endregion

		#region ToBase64

		/// <summary>
		/// 将字符串用Base64编码
		/// </summary>
		public static string ToBase64(this string input, Encoding originalEncodingUsing = null)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			byte[] tempArray = originalEncodingUsing.NullCheck(Encoding.UTF8).GetBytes(input);
			return Convert.ToBase64String(tempArray);
		}

		#endregion

		#region ToByteArray

		/// <summary>
		/// 将字符串编码为字节数组（默认编码为UTF8)
		/// </summary>
		public static byte[] ToByteArray(this string input, Encoding encodingUsing = null)
		{
			return string.IsNullOrEmpty(input) ? null : encodingUsing.NullCheck(Encoding.UTF8).GetBytes(input);
		}

		#endregion

		#region ToFirstCharacterUpperCase

		/// <summary>
		/// 将字符串转换为首字母大写
		/// </summary>
		public static string ToFirstCharacterUpperCase(this string input)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			char[] inputChars = input.ToCharArray();
			for (int x = 0; x < inputChars.Length; ++x)
			{
				if (inputChars[x] != ' ' && inputChars[x] != '\t')
				{
					inputChars[x] = char.ToUpper(inputChars[x]);
					break;
				}
			}
			return new string(inputChars);
		}

		#endregion

		#region ToSentenceCapitalize

		/// <summary>
		/// Capitalizes each sentence within the string
		/// </summary>
		public static string ToSentenceCapitalize(this string input)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			string[] seperator = { ".", "?", "!" };
			string[] inputStrings = input.Split(seperator, StringSplitOptions.None);
			for (int x = 0; x < inputStrings.Length; ++x)
			{
				if (!string.IsNullOrEmpty(inputStrings[x]))
				{
					Regex tempRegex = new Regex(inputStrings[x]);
					inputStrings[x] = inputStrings[x].ToFirstCharacterUpperCase();
					input = tempRegex.Replace(input, inputStrings[x]);
				}
			}
			return input;
		}

		#endregion

		#region ToTitleCase

		/// <summary>
		/// 转换字符串为标题样式（全部单词首字母大写）
		/// </summary>
		public static string ToTitleCase(this string input)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			string[] seperator = { " ", ".", "\t", System.Environment.NewLine, "!", "?" };
			string[] inputStrings = input.Split(seperator, StringSplitOptions.None);
			for (int x = 0; x < inputStrings.Length; ++x)
			{
				if (!string.IsNullOrEmpty(inputStrings[x])
					&& inputStrings[x].Length > 3)
				{
					Regex tempRegex = new Regex(inputStrings[x]);
					inputStrings[x] = inputStrings[x].ToFirstCharacterUpperCase();
					input = tempRegex.Replace(input, inputStrings[x]);
				}
			}
			return input;
		}

		#endregion

		#region NumberTimesOccurs

		/// <summary>
		/// 统计子字符串的出现次数
		/// (子字符串可以是正则表达式)
		/// </summary>
		public static int NumberTimesOccurs(this string input, string match)
		{
			return string.IsNullOrEmpty(input) ? 0 : new Regex(match).Matches(input).Count;
		}

		#endregion

		#region Reverse

		/// <summary>
		/// 反转字符串
		/// </summary>
		public static string Reverse(this string input)
		{
			return new string(input.Reverse<char>().ToArray());
		}

		#endregion

		#region FilterOutText

		/// <summary>
		/// 删除全部匹配的子字符串
		/// (子字符串可以是正则表达式)
		/// </summary>
		public static string FilterOutText(this string input, string filter)
		{
			if (string.IsNullOrEmpty(input))
				return "";
			return string.IsNullOrEmpty(filter) ? input : new Regex(filter).Replace(input, "");
		}

		#endregion

		#region KeepFilterText

		/// <summary>
		/// 返回全部匹配的子字符串
		/// (子字符串可以是正则表达式)
		/// </summary>
		public static string KeepFilterText(this string input, string filter)
		{
			if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(filter))
				return "";
			Regex tempRegex = new Regex(filter);
			MatchCollection collection = tempRegex.Matches(input);
			StringBuilder builder = new StringBuilder();
			foreach (Match match in collection)
				builder.Append(match.Value);
			return builder.ToString();
		}

		#endregion

		#region AlphaNumericOnly

		/// <summary>
		/// 只保留字母和十进制数字
		/// </summary>
		public static string AlphaNumericOnly(this string input)
		{
			return input.KeepFilterText("[a-zA-Z0-9]");
		}

		#endregion

		#region AlphaCharactersOnly

		/// <summary>
		///  只保留字母
		/// </summary>
		public static string AlphaCharactersOnly(this string input)
		{
			return input.KeepFilterText("[a-zA-Z]");
		}

		#endregion

		#region NumericOnly

		/// <summary>
		/// 只保留数字和“.”
		/// <param name="keepNumericPunctuation">是否保留“.”</param>
		/// </summary>
		public static string NumericOnly(this string input, bool keepNumericPunctuation = true)
		{
			return keepNumericPunctuation ? input.KeepFilterText(@"[0-9\.]") : input.KeepFilterText("[0-9]");
		}

		#endregion

		#region IsUnicode

		/// <summary>
		/// 判断字符串是否全部为Unicode字符组成
		/// </summary>
		public static bool IsUnicode(this string input)
		{
			return string.IsNullOrEmpty(input) ? true : Regex.Replace(input, @"[^\u0000-\u007F]", "") != input;
		}

		#endregion

		//#region FormatString

		///// <summary>
		///// 用格式化字符串输出
		///// # = digits
		///// @ = alpha characters
		///// \ = escape char
		///// </summary>
		//public static string FormatString(this string input, string format)
		//{
		//    return new GenericStringFormatter().Format(input, format);
		//}

		//#endregion

		#region RegexFormat

		/// <summary>
		/// 用正则表达式格式化字符串
		/// </summary>
		public static string RegexFormat(this string input, string format, string outputFormat, RegexOptions options = RegexOptions.None)
		{
			input.ThrowIfNullOrEmpty("Input");
			return Regex.Replace(input, format, outputFormat, options);
		}

		#endregion

		#endregion
	}
}
